/**
 * 神煞计算核心模块 - 最简设计
 */
import { ChildLimit, SolarTime, Gender } from "./bazi-utils";
import { nayinMap, ssSequenceList, sysSSList } from "./config";




/**
 * 检查性别是否匹配神煞要求
 * @param shensha 神煞配置
 * @param positions 位置信息
 * @param sex 性别
 * @returns 是否匹配性别要求
 */
function checkGenderMatch(shensha: any, positions: Record<number, string | null>, sex: number): boolean {
  // 安全检查：确保 shensha 对象存在且有所需属性
  if (!shensha || typeof shensha !== 'object' || !shensha.hasOwnProperty('sex')) {
    return false; // 如果神煞对象无效，跳过
  }
  
  if (shensha.sex === "0") {
    return true; // 通用神煞，男女都适用
  }
  
  const shenshaSex = parseInt(shensha.sex);
  
  // 特殊处理：元辰的性别检查需要根据阴阳来判断
  if (shensha.name === '元辰') {
    // 元辰的性别检查：sex=1表示阴男阳女，sex=2表示阳男阴女
    const yearGan = positions[1] as string;
    const isYangGan = ['甲', '丙', '戊', '庚', '壬'].includes(yearGan);
    
    if (shenshaSex === 1) {
      // 阴男阳女专用：年干为阴且性别为男，或年干为阳且性别为女
      return (!isYangGan && sex === 0) || (isYangGan && sex === 1);
    } else if (shenshaSex === 2) {
      // 阳男阴女专用：年干为阳且性别为男，或年干为阴且性别为女
      return (isYangGan && sex === 0) || (!isYangGan && sex === 1);
    }
  } else {
    // 其他神煞的性别检查
    return shenshaSex === sex;
  }
  
  return false;
}


/**
 * 神煞计算 - 最简设计
 * @param childLimit ChildLimit对象
 * @param ganzhi 干支信息，如 "戊寅"（流年/大运/身宫/命宫/胎元/流日/流月/小运等）
 * @returns 神煞名称数组
 */
export function calculateShensha(
  childLimit: ChildLimit,
  ganzhi: string
): string[] {
  try {
    // 获取八字信息
    const eightChar = childLimit.getEightChar();
    const yearGZ = eightChar.getYear();
    const monthGZ = eightChar.getMonth();
    const dayGZ = eightChar.getDay();
    const hourGZ = eightChar.getHour();

    // 获取性别
    const gender = childLimit.getGender();
    // API性别参数映射：sex=0男性，sex=1女性，sex=2男性
    const sex = gender === Gender.MAN ? 0 : 1;

    // 验证干支格式（必须是两个字）
    if (!ganzhi || ganzhi.length !== 2) {
      console.error('干支格式错误，必须是两个字，如 "戊寅"');
      return [];
    }

    // 构建位置映射
    const positions = buildPositions(yearGZ, monthGZ, dayGZ, hourGZ, ganzhi);

    // 计算神煞（包含优先级处理）
    const yearNayin = nayinMap[yearGZ.getHeavenStem().getName() + yearGZ.getEarthBranch().getName()];
    return doCalculateShensha(positions, sex, ganzhi, yearNayin);
  } catch (error) {
    console.error('神煞计算失败:', error);
    return [];
  }
}

/**
 * 四柱神煞计算 - 专门计算年月日时柱的神煞
 * @param childLimit ChildLimit对象
 * @param pillarType 柱类型：'year' | 'month' | 'day' | 'hour'
 * @returns 神煞名称数组
 */
export function calculatePillarShensha(
  childLimit: ChildLimit,
  pillarType: 'year' | 'month' | 'day' | 'hour'
): string[] {
  try {
    // 获取八字信息
    const eightChar = childLimit.getEightChar();
    const yearGZ = eightChar.getYear();
    const monthGZ = eightChar.getMonth();
    const dayGZ = eightChar.getDay();
    const hourGZ = eightChar.getHour();

    // 获取性别
    const gender = childLimit.getGender();
    const sex = gender === Gender.MAN ? 0 : 1;

    // 根据柱类型获取对应的干支
    let targetGZ: any;
    switch (pillarType) {
      case 'year':
        targetGZ = yearGZ;
        break;
      case 'month':
        targetGZ = monthGZ;
        break;
      case 'day':
        targetGZ = dayGZ;
        break;
      case 'hour':
        targetGZ = hourGZ;
        break;
      default:
        throw new Error('无效的柱类型');
    }

    // 构建位置映射（使用目标柱的干支作为"流年"）
    const ganzhi = targetGZ.getHeavenStem().getName() + targetGZ.getEarthBranch().getName();
    const positions = buildPositions(yearGZ, monthGZ, dayGZ, hourGZ, ganzhi);

    // 计算神煞
    const yearNayin = nayinMap[yearGZ.getHeavenStem().getName() + yearGZ.getEarthBranch().getName()];
    return doCalculatePillarShensha(positions, sex, ganzhi, yearNayin, pillarType);
  } catch (error) {
    console.error('四柱神煞计算失败:', error);
    return [];
  }
}

/**
 * 计算所有四柱的神煞 - 便捷方法
 * @param childLimit ChildLimit对象
 * @returns 四柱神煞对象
 */
export function calculateAllPillarShensha(childLimit: ChildLimit): {
  year: string[];
  month: string[];
  day: string[];
  hour: string[];
} {
  try {
    return {
      year: calculatePillarShensha(childLimit, 'year'),
      month: calculatePillarShensha(childLimit, 'month'),
      day: calculatePillarShensha(childLimit, 'day'),
      hour: calculatePillarShensha(childLimit, 'hour')
    };
  } catch (error) {
    console.error('四柱神煞计算失败:', error);
    return {
      year: [],
      month: [],
      day: [],
      hour: []
    };
  }
}

/**
 * 构建位置映射表
 */
function buildPositions(
  yearGZ: any, monthGZ: any, dayGZ: any, hourGZ: any, 
  ganzhi: string
): Record<number, string | null> {
  const yearStem = yearGZ.getHeavenStem().getName();
  const yearBranch = yearGZ.getEarthBranch().getName();
  const monthStem = monthGZ.getHeavenStem().getName();
  const monthBranch = monthGZ.getEarthBranch().getName();
  const dayStem = dayGZ.getHeavenStem().getName();
  const dayBranch = dayGZ.getEarthBranch().getName();
  const hourStem = hourGZ.getHeavenStem().getName();
  const hourBranch = hourGZ.getEarthBranch().getName();

  // 解析传入的干支（流年/大运/身宫/命宫/胎元/流日/流月/小运等）
  const ganzhiStem = ganzhi.charAt(0);
  const ganzhiBranch = ganzhi.charAt(1);

  return {
    1: yearStem, 2: monthStem, 3: dayStem, 4: hourStem, 5: null, 6: ganzhiStem,
    7: yearBranch, 8: monthBranch, 9: dayBranch, 10: hourBranch, 11: null, 12: ganzhiBranch,
    13: yearStem + yearBranch, 14: monthStem + monthBranch, 15: dayStem + dayBranch, 16: hourStem + hourBranch,
    17: nayinMap[yearStem + yearBranch] || null, 18: [yearStem, monthStem, dayStem, hourStem].join(''), 19: ganzhi, 20: nayinMap[monthStem + monthBranch] || null,
    21: nayinMap[dayStem + dayBranch] || null, 22: nayinMap[hourStem + hourBranch] || null,
    23: yearStem + yearBranch, 24: monthStem + monthBranch, 25: dayStem + dayBranch, 26: hourStem + hourBranch
  };
}

/**
 * 四柱神煞计算核心逻辑 - 专门为四柱设计
 */
function doCalculatePillarShensha(
  positions: Record<number, string | null>, 
  sex: number,
  targetGanzhi: string,
  yearNayin: string,
  pillarType: 'year' | 'month' | 'day' | 'hour'
): string[] {
  const result: string[] = [];

  for (const shensha of sysSSList) {
    // 安全检查：确保神煞对象有效
    if (!shensha || typeof shensha !== 'object') {
      continue;
    }
    
    // 性别检查
    if (!checkGenderMatch(shensha, positions, sex)) {
      continue;
    }

    const mainPositions = shensha.main.split(",").map(Number);
    const tagPositions = shensha.tags === "0" ? [] : shensha.tags.split(",").map(Number);

    // 四柱神煞计算：根据柱类型过滤相关神煞
    if (!isRelevantForPillar(shensha, pillarType)) {
      continue;
    }

    // 通用神煞计算逻辑
    for (const mainPos of mainPositions) {
      let searchKey = "";

      // 根据位置类型获取搜索键
      if (mainPos === 8) {
        // 月支位置 - 直接使用月支名称
        searchKey = positions[8] as string;
        } else if (mainPos === 17) {
          // 年纳音位置
          searchKey = positions[17] as string;
        } else if (mainPos === 18) {
          // 完全基于配置数据处理天干神煞
          const allStems = positions[18] as string;
          const found = Object.keys(shensha.data).some(combination => {
            return combination.split("").every(stem => allStems.includes(stem));
          });
          // 基于配置数据的tags判断在哪些柱显示
          if (found) {
            // 三奇贵人只在日柱显示，且需要严格按顺序匹配
            if (shensha.name === '三奇贵人') {
              if (pillarType === 'day') {
                // 三奇贵人需要严格按顺序匹配：甲戊庚、乙丙丁、壬癸辛
                const allStems = positions[18] as string;
                const sanqiCombinations = ['甲戊庚', '乙丙丁', '壬癸辛'];
                let isSanqiMatch = false;
                
                for (const combination of sanqiCombinations) {
                  // 严格按顺序匹配：检查是否包含完整的三奇组合
                  if (allStems.includes(combination)) {
                    isSanqiMatch = true;
                    break;
                  }
                }
                
                // 根据API行为，三奇贵人出现频率很低，需要更严格的匹配条件
                if (isSanqiMatch && !result.includes(shensha.name)) {
                  result.push(shensha.name);
                }
              }
            } else {
              // 其他天干神煞所有柱都相关
              if (!result.includes(shensha.name)) {
                result.push(shensha.name);
              }
            }
          }
          continue;
      } else {
        searchKey = positions[mainPos] as string;
      }

      if (searchKey && (shensha.data as any)[searchKey] !== undefined) {
        const targetValue = (shensha.data as any)[searchKey];
        let foundMatch = false;

        // 四柱神煞匹配逻辑 - 完全基于配置数据
        for (const tagPos of tagPositions) {
          const checkValue = positions[tagPos] as string;
          if (checkValue && (targetValue === checkValue || targetValue.includes(checkValue))) {
            // 特殊处理：福星贵人在所有匹配的柱中都显示（匹配API行为）
            if (shensha.name === '福星贵人') {
              if (targetValue.includes(checkValue)) {
                // 检查匹配的地支是否在当前柱的地支位置
                if (isPositionRelevantForPillar(tagPos, pillarType)) {
                  foundMatch = true;
                  break;
                }
              }
            } else if (shensha.name === '元辰') {
              // 元辰正确计算方法：基于传统公式，不使用地支关系匹配
              const yearGan = positions[1] as string; // 年干
              const yearZhi = positions[7] as string; // 年支
              
              // 地支列表和索引
              const zhiList = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
              const yearZhiIndex = zhiList.indexOf(yearZhi);
              
              if (yearZhiIndex === -1) {
                continue; // 年支无效，跳过
              }
              
              // 判断年干阴阳：阳干为甲、丙、戊、庚、壬；阴干为乙、丁、己、辛、癸
              const isYangGan = ['甲', '丙', '戊', '庚', '壬'].includes(yearGan);
              // 判断性别：sex为0表示男，1表示女
              const isMale = sex === 0;
              
              // 确定是阳男阴女还是阴男阳女
              let yuanChenIndex;
              if ((isMale && isYangGan) || (!isMale && !isYangGan)) {
                // 阳男阴女：元辰 = 年支索引 + 7
                yuanChenIndex = (yearZhiIndex + 7) % 12;
              } else {
                // 阴男阳女：元辰 = 年支索引 + 5
                yuanChenIndex = (yearZhiIndex + 5) % 12;
              }
              
              const yuanChenZhi = zhiList[yuanChenIndex];
              
              // 检查当前柱的地支是否匹配元辰
              if (checkValue === yuanChenZhi) {
                // 检查匹配的地支是否在当前柱的地支位置
                if (isPositionRelevantForPillar(tagPos, pillarType)) {
                  foundMatch = true;
                  break;
                }
              }
            } else {
              // 检查匹配的地支是否在当前柱的地支位置
              if (isPositionRelevantForPillar(tagPos, pillarType)) {
                foundMatch = true;
                break;
              }
            }
          }
        }

        // 特殊处理：月支相关神煞（main为8）
        if (mainPos === 8) {
          // 月支神煞需要检查tags位置是否匹配，并且tags位置要与当前柱相关
          for (const tagPos of tagPositions) {
            const checkValue = positions[tagPos] as string;
            if (checkValue && (targetValue === checkValue || targetValue.includes(checkValue))) {
              // 检查这个tag位置是否与当前柱相关
              if (isPositionRelevantForPillar(tagPos, pillarType)) {
                foundMatch = true;
                break;
              }
            }
          }
        }

        
        // 特殊处理：元辰神煞的计算逻辑
        if (shensha.name === "元辰" && mainPos === 7) {
          // 元辰正确计算方法：基于传统公式，不使用配置数据
          const yearGan = positions[1] as string; // 年干
          const yearZhi = positions[7] as string; // 年支
          
          // 地支列表和索引
          const zhiList = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
          const yearZhiIndex = zhiList.indexOf(yearZhi);
          
          if (yearZhiIndex === -1) {
            continue; // 年支无效，跳过
          }
          
          // 判断年干阴阳：阳干为甲、丙、戊、庚、壬；阴干为乙、丁、己、辛、癸
          const isYangGan = ['甲', '丙', '戊', '庚', '壬'].includes(yearGan);
          // 判断性别：sex为0表示男，1表示女
          const isMale = sex === 0;
          
          // 确定是阳男阴女还是阴男阳女
          let yuanChenIndex;
          if ((isMale && isYangGan) || (!isMale && !isYangGan)) {
            // 阳男阴女：元辰 = 年支索引 + 7
            yuanChenIndex = (yearZhiIndex + 7) % 12;
          } else {
            // 阴男阳女：元辰 = 年支索引 + 5
            yuanChenIndex = (yearZhiIndex + 5) % 12;
          }
          
          const yuanChenZhi = zhiList[yuanChenIndex];
          
          // 检查期望的地支是否在当前柱的地支位置
          for (const tagPos of tagPositions) {
            const checkValue = positions[tagPos] as string;
            if (checkValue && checkValue === yuanChenZhi) {
              if (isPositionRelevantForPillar(tagPos, pillarType)) {
                foundMatch = true;
                break;
              }
            }
          }
        }
        // 特殊处理：年纳音相关神煞（main为17）
        else if (mainPos === 17) {
          // 年纳音神煞需要根据配置值的长度进行不同匹配
          for (const tagPos of tagPositions) {
            const checkValue = positions[tagPos] as string;
            if (checkValue) {
              // 根据配置值的长度决定匹配方式
              if (targetValue.length === 1) {
                // 单字配置（如学堂、词馆）：精确匹配地支
                if (targetValue === checkValue) {
                  if (isPositionRelevantForPillar(tagPos, pillarType)) {
                    foundMatch = true;
                    break;
                  }
                }
              } else if (targetValue.length === 2) {
                // 双字配置（如正学堂、正词馆）：精确匹配完整干支
                if (targetValue === checkValue) {
                  if (isPositionRelevantForPillar(tagPos, pillarType)) {
                    foundMatch = true;
                    break;
                  }
                }
              } else {
                // 其他情况：使用包含匹配
                if (targetValue === checkValue || targetValue.includes(checkValue)) {
                  if (isPositionRelevantForPillar(tagPos, pillarType)) {
                    foundMatch = true;
                    break;
                  }
                }
              }
            }
          }
        }

        // 特殊处理：日柱神煞（tags为"0"）
        if (shensha.tags === "0") {
          // 完全基于配置数据处理tags="0"的神煞
          const relevantPillars = shensha.name === '金神' ? ['day', 'hour'] : ['day'];
          if (relevantPillars.includes(pillarType)) {
            if ((shensha.data as any)[targetGanzhi] !== undefined) {
              foundMatch = true;
            }
          }
        }


        if (foundMatch && !result.includes(shensha.name)) {
          // 特殊处理：学堂类神煞的优先级
          if (shensha.name === '学堂' || shensha.name === '词馆') {
            // 检查是否已经有对应的"正"版本
            const positiveName = shensha.name === '学堂' ? '正学堂' : '正词馆';
            if (result.includes(positiveName)) {
              // 如果已经有正版本，跳过普通版本
              continue;
            }
          } else if (shensha.name === '正学堂' || shensha.name === '正词馆') {
            // 如果添加正版本，移除普通版本
            const normalName = shensha.name === '正学堂' ? '学堂' : '词馆';
            const normalIndex = result.indexOf(normalName);
            if (normalIndex > -1) {
              result.splice(normalIndex, 1);
            }
          }
          
          result.push(shensha.name);
        }
      }
    }
  }

  // 去重
  let uniqueShensha = Array.from(new Set(result));

  // 特殊处理：学堂类神煞的优先级
  const finalResult: string[] = [];
  
  // 先处理正版本
  for (const shensha of uniqueShensha) {
    if (shensha === '正学堂' || shensha === '正词馆') {
      finalResult.push(shensha);
    }
  }
  
  // 再处理普通版本，但跳过已有正版本的
  for (const shensha of uniqueShensha) {
    if (shensha === '学堂' || shensha === '词馆') {
      const positiveName = shensha === '学堂' ? '正学堂' : '正词馆';
      if (!finalResult.includes(positiveName)) {
        finalResult.push(shensha);
      }
    } else if (shensha !== '正学堂' && shensha !== '正词馆') {
      finalResult.push(shensha);
    }
  }

  // 排序
  finalResult.sort((a, b) => {
    const indexA = ssSequenceList.indexOf(a);
    const indexB = ssSequenceList.indexOf(b);
    return (indexA === -1 ? 999 : indexA) - (indexB === -1 ? 999 : indexB);
  });

  return finalResult;
}


/**
 * 判断位置是否与指定柱相关
 */
function isPositionRelevantForPillar(position: number, pillarType: 'year' | 'month' | 'day' | 'hour'): boolean {
  const pillarPositions = {
    'year': [1, 7, 13, 17, 23], // 年干、年支、年柱、年纳音、年干支一柱
    'month': [2, 8, 14, 20, 24], // 月干、月支、月柱、月纳音、月干支一柱
    'day': [3, 9, 15, 21, 25], // 日干、日支、日柱、日纳音、日干支一柱
    'hour': [4, 10, 16, 22, 26] // 时干、时支、时柱、时纳音、时干支一柱
  };

  const relevantPositions = pillarPositions[pillarType];
  
  // 特殊处理：位置6在四柱计算中对应流年干，但可以用于其他柱的匹配
  if (position === 6) {
    return true; // 位置6（流年干）可以用于所有柱的匹配
  }
  
  // 特殊处理：位置12（流年支）在四柱计算中不适用
  if (position === 12) {
    return false; // 位置12（流年支）在四柱计算中不适用
  }
  
  return relevantPositions.includes(position);
}

/**
 * 判断神煞是否与指定柱相关
 */
function isRelevantForPillar(shensha: any, pillarType: 'year' | 'month' | 'day' | 'hour'): boolean {
  const mainPositions = shensha.main.split(",").map(Number);
  const tagPositions = shensha.tags === "0" ? [] : shensha.tags.split(",").map(Number);

  // 定义各柱对应的位置ID
  const pillarPositions = {
    'year': [1, 7, 13, 17, 23], // 年干、年支、年柱、年纳音、年干支一柱
    'month': [2, 8, 14, 20, 24], // 月干、月支、月柱、月纳音、月干支一柱
    'day': [3, 9, 15, 21, 25], // 日干、日支、日柱、日纳音、日干支一柱
    'hour': [4, 10, 16, 22, 26] // 时干、时支、时柱、时纳音、时干支一柱
  };

  const relevantPositions = pillarPositions[pillarType];

  // 特殊处理：日柱神煞（tags为"0"）
  if (shensha.tags === "0") {
    // 金神可以在日柱和时柱显示
    if (shensha.name === '金神') {
      return pillarType === 'day' || pillarType === 'hour';
    } else {
      // 其他日柱神煞只在日柱显示
      return pillarType === 'day';
    }
  }

  // 特殊处理：年纳音相关神煞（main为17）
  if (mainPositions.includes(17)) {
    // 年纳音神煞可以在任何柱显示，只要tags位置与柱相关
    const tagRelevant = tagPositions.some((pos: number) => isPositionRelevantForPillar(pos, pillarType));
    return tagRelevant;
  }

        // 特殊处理：天干相关神煞（main为18）
        if (mainPositions.includes(18)) {
          // 三奇贵人只在日柱显示
          if (shensha.name === '三奇贵人') {
            return pillarType === 'day';
          }
          // 其他天干神煞所有柱都相关
          return true;
        }

        
        // 特殊处理：元辰可以在任何柱显示，根据匹配条件决定
        if (shensha.name === '元辰') {
          return true;
        }

  // 检查主位置是否与柱相关
  const mainRelevant = mainPositions.some((pos: number) => relevantPositions.includes(pos));
  
  // 检查标签位置是否与柱相关
  const tagRelevant = tagPositions.some((pos: number) => isPositionRelevantForPillar(pos, pillarType));

  // 只有主位置或标签位置与柱相关时才返回true
  return mainRelevant || tagRelevant;
}

/**
 * 神煞计算核心逻辑
 */
function doCalculateShensha(
  positions: Record<number, string | null>, 
  sex: number,
  liunian: string,
  yearNayin: string
): string[] {
  const result: string[] = [];

  for (const shensha of sysSSList) {
    // 安全检查：确保神煞对象有效
    if (!shensha || typeof shensha !== 'object') {
      continue;
    }
    
    // 性别检查
    if (!checkGenderMatch(shensha, positions, sex)) {
      continue;
    }
    

    const mainPositions = shensha.main.split(",").map(Number);
    const tagPositions = shensha.tags === "0" ? [] : shensha.tags.split(",").map(Number);

    // 排除所有日柱神煞（tags为"0"）
    if (shensha.tags === "0") {
      continue;
    }

    // 通用神煞计算逻辑
    for (const mainPos of mainPositions) {
      let searchKey = "";

      // 根据位置类型获取搜索键
      if (mainPos === 8) {
        // 月支位置 - 直接使用月支名称
        searchKey = positions[8] as string;
      } else if (mainPos === 17) {
        // 年纳音位置
        searchKey = positions[17] as string;
      } else if (mainPos === 18) {
        // 天干位置 - 检查三奇贵人
        const allStems = positions[18] as string;
        const found = Object.keys(shensha.data).some(combination => {
          return combination.split("").every(stem => allStems.includes(stem));
        });
        // 三奇贵人只在日柱显示，在流年计算中跳过
        if (found && shensha.name === '三奇贵人') {
          continue; // 跳过三奇贵人，它只在日柱计算中处理
        }
        continue;
      } else {
        // 其他位置直接使用
        searchKey = positions[mainPos] as string;
      }

      if (searchKey && (shensha.data as any)[searchKey] !== undefined) {
        const targetValue = (shensha.data as any)[searchKey];
        let foundMatch = false;

        // 特殊处理：元辰神煞的计算逻辑（流年版本）
        if (shensha.name === "元辰" && mainPos === 7) {
          // 元辰正确计算方法：基于传统公式，与四柱神煞保持一致
          const yearGan = positions[1] as string; // 年干
          const yearZhi = positions[7] as string; // 年支
          const liunianZhi = positions[12] as string; // 流年支
          
          // 地支列表和索引
          const zhiList = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
          const yearZhiIndex = zhiList.indexOf(yearZhi);
          
          if (yearZhiIndex === -1 || !liunianZhi) {
            continue; // 年支无效或流年支为空，跳过
          }
          
          // 判断年干阴阳：阳干为甲、丙、戊、庚、壬；阴干为乙、丁、己、辛、癸
          const isYangGan = ['甲', '丙', '戊', '庚', '壬'].includes(yearGan);
          // 判断性别：sex为0表示男，1表示女
          const isMale = sex === 0;
          
          // 确定是阳男阴女还是阴男阳女
          let yuanChenIndex;
          if ((isMale && isYangGan) || (!isMale && !isYangGan)) {
            // 阳男阴女：元辰 = 年支索引 + 7
            yuanChenIndex = (yearZhiIndex + 7) % 12;
          } else {
            // 阴男阳女：元辰 = 年支索引 + 5
            yuanChenIndex = (yearZhiIndex + 5) % 12;
          }
          
          const yuanChenZhi = zhiList[yuanChenIndex];
          
          // 检查流年支是否匹配元辰
          if (liunianZhi === yuanChenZhi) {
            foundMatch = true;
          }
        } else {
          // 通用匹配逻辑 - 完全基于tags配置
          for (const tagPos of tagPositions) {
            const checkValue = positions[tagPos] as string;
            if (checkValue && (targetValue === checkValue || targetValue.includes(checkValue))) {
              foundMatch = true;
              break;
            }
          }
        }
        
        // 特殊处理：福星贵人在流年神煞中的特殊逻辑（无论foundMatch状态都要检查）
        if (shensha.name === "福星贵人") {
          // 福星贵人需要检查年干和日干对应的地支是否在流年支中
          const yearGan = positions[1] as string; // 年干
          const dayGan = positions[3] as string; // 日干
          const liunianZhi = positions[12] as string; // 流年支
          
          // 根据福星贵人配置检查
          const yearGanData = (shensha.data as any)[yearGan];
          const dayGanData = (shensha.data as any)[dayGan];
          
          if (yearGanData && liunianZhi && yearGanData.includes(liunianZhi)) {
            foundMatch = true;
          } else if (dayGanData && liunianZhi && dayGanData.includes(liunianZhi)) {
            foundMatch = true;
          }
        }
        
        // 流年神煞计算：基于API行为模式的精确逻辑
        if (foundMatch) {
          // 检查是否通过流年相关位置匹配
          let matchedByLiunian = false;
          
          // 特殊处理：福星贵人在流年神煞中的特殊逻辑
          if (shensha.name === "福星贵人") {
            // 福星贵人需要检查年干和日干对应的地支是否在流年支中
            const yearGan = positions[1] as string; // 年干
            const dayGan = positions[3] as string; // 日干
            const liunianZhi = positions[12] as string; // 流年支
            
            // 根据福星贵人配置检查
            const yearGanData = (shensha.data as any)[yearGan];
            const dayGanData = (shensha.data as any)[dayGan];
            
            if (yearGanData && liunianZhi && yearGanData.includes(liunianZhi)) {
              matchedByLiunian = true;
            } else if (dayGanData && liunianZhi && dayGanData.includes(liunianZhi)) {
              matchedByLiunian = true;
            }
          }
          
          // 特殊处理：元辰神煞在流年神煞中的特殊逻辑
          if (shensha.name === "元辰") {
            // 元辰正确计算方法：基于传统公式，与四柱神煞保持一致
            const yearGan = positions[1] as string; // 年干
            const yearZhi = positions[7] as string; // 年支
            const liunianZhi = positions[12] as string; // 流年支
            
            // 地支列表和索引
            const zhiList = ['子', '丑', '寅', '卯', '辰', '巳', '午', '未', '申', '酉', '戌', '亥'];
            const yearZhiIndex = zhiList.indexOf(yearZhi);
            
            if (yearZhiIndex !== -1 && liunianZhi) {
              // 判断年干阴阳：阳干为甲、丙、戊、庚、壬；阴干为乙、丁、己、辛、癸
              const isYangGan = ['甲', '丙', '戊', '庚', '壬'].includes(yearGan);
              // 判断性别：sex为0表示男，1表示女
              const isMale = sex === 0;
              
              // 确定是阳男阴女还是阴男阳女
              let yuanChenIndex;
              if ((isMale && isYangGan) || (!isMale && !isYangGan)) {
                // 阳男阴女：元辰 = 年支索引 + 7
                yuanChenIndex = (yearZhiIndex + 7) % 12;
              } else {
                // 阴男阳女：元辰 = 年支索引 + 5
                yuanChenIndex = (yearZhiIndex + 5) % 12;
              }
              
              const yuanChenZhi = zhiList[yuanChenIndex];
              
              // 检查流年支是否匹配元辰
              if (liunianZhi === yuanChenZhi) {
                matchedByLiunian = true;
              }
            }
          }
          
          // 特殊处理：天德合在流年神煞中的特殊逻辑
          if (shensha.name === "天德合") {
            // 天德合需要检查月支对应的天干是否在流年干中（使用id 44的配置）
            const monthZhi = positions[8] as string; // 月支
            const liunianGan = positions[6] as string; // 流年干
            const liunianZhi = positions[12] as string; // 流年支
            
            const monthZhiData = (shensha.data as any)[monthZhi];
            if (monthZhiData && liunianGan && monthZhiData === liunianGan) {
              matchedByLiunian = true;
            }
            
            // 也检查月支对应的地支是否在流年支中（使用id 156的配置）
            // 这里需要查找id 156的配置
            const monthZhiData2 = (shensha.data as any)[monthZhi];
            if (monthZhiData2 && liunianZhi && monthZhiData2 === liunianZhi) {
              matchedByLiunian = true;
            }
          }
          
          // 特殊处理：月德合在流年神煞中的特殊逻辑
          if (shensha.name === "月德合") {
            // 月德合需要检查月支对应的天干是否在流年干中
            const monthZhi = positions[8] as string; // 月支
            const liunianGan = positions[6] as string; // 流年干
            
            const monthZhiData = (shensha.data as any)[monthZhi];
            if (monthZhiData && liunianGan && monthZhiData === liunianGan) {
              matchedByLiunian = true;
            }
          }
          
          // 特殊处理：正词馆在流年神煞中的特殊逻辑
          if (shensha.name === "正词馆") {
            // 正词馆需要检查年纳音对应的干支是否在流年中
            const yearNayin = positions[17] as string; // 年纳音
            const liunian = positions[6] as string + positions[12] as string; // 流年干支
            
            const yearNayinData = (shensha.data as any)[yearNayin];
            if (yearNayinData && liunian && yearNayinData === liunian) {
              matchedByLiunian = true;
            }
          }
          
          // 特殊处理：正学堂在流年神煞中的特殊逻辑
          if (shensha.name === "正学堂") {
            // 正学堂需要检查年纳音对应的干支是否在流年中
            const yearNayin = positions[17] as string; // 年纳音
            const liunian = positions[6] as string + positions[12] as string; // 流年干支
            
            const yearNayinData = (shensha.data as any)[yearNayin];
            if (yearNayinData && liunian && yearNayinData === liunian) {
              matchedByLiunian = true;
            }
          }
          
          // 检查是否通过流年支或流年干匹配
          for (const tagPos of tagPositions) {
            const checkValue = positions[tagPos] as string;
            if (checkValue && (targetValue === checkValue || targetValue.includes(checkValue))) {
              if (tagPos === 12 || tagPos === 6) { // 流年支或流年干位置
                matchedByLiunian = true;
                break;
              }
              // 特殊处理：元辰神煞也允许通过年支位置匹配
              if (shensha.name === "元辰" && tagPos === 7) {
                matchedByLiunian = true;
                break;
              }
            }
          }
          
          // 只有通过流年相关位置匹配的神煞才被添加
          if (matchedByLiunian && !result.includes(shensha.name)) {
            result.push(shensha.name);
          }
        } else {
          // 特殊处理：即使没有通过常规匹配，也要检查特殊神煞
          let matchedByLiunian = false;
          
          // 特殊处理：天德合在流年神煞中的特殊逻辑
          if (shensha.name === "天德合") {
            // 天德合需要检查月支对应的天干是否在流年干中（使用id 44的配置）
            const monthZhi = positions[8] as string; // 月支
            const liunianGan = positions[6] as string; // 流年干
            const liunianZhi = positions[12] as string; // 流年支
            
            const monthZhiData = (shensha.data as any)[monthZhi];
            if (monthZhiData && liunianGan && monthZhiData === liunianGan) {
              matchedByLiunian = true;
            }
            
            // 也检查月支对应的地支是否在流年支中（使用id 156的配置）
            // 这里需要查找id 156的配置
            const monthZhiData2 = (shensha.data as any)[monthZhi];
            if (monthZhiData2 && liunianZhi && monthZhiData2 === liunianZhi) {
              matchedByLiunian = true;
            }
          }
          
          // 特殊处理：月德合在流年神煞中的特殊逻辑
          if (shensha.name === "月德合") {
            // 月德合需要检查月支对应的天干是否在流年干中
            const monthZhi = positions[8] as string; // 月支
            const liunianGan = positions[6] as string; // 流年干
            
            const monthZhiData = (shensha.data as any)[monthZhi];
            if (monthZhiData && liunianGan && monthZhiData === liunianGan) {
              matchedByLiunian = true;
            }
          }
          
          // 特殊处理：正词馆在流年神煞中的特殊逻辑
          if (shensha.name === "正词馆") {
            // 正词馆需要检查年纳音对应的干支是否在流年中
            const yearNayin = positions[17] as string; // 年纳音
            const liunian = positions[6] as string + positions[12] as string; // 流年干支
            
            const yearNayinData = (shensha.data as any)[yearNayin];
            if (yearNayinData && liunian && yearNayinData === liunian) {
              matchedByLiunian = true;
            }
          }
          
          // 特殊处理：正学堂在流年神煞中的特殊逻辑
          if (shensha.name === "正学堂") {
            // 正学堂需要检查年纳音对应的干支是否在流年中
            const yearNayin = positions[17] as string; // 年纳音
            const liunian = positions[6] as string + positions[12] as string; // 流年干支
            
            const yearNayinData = (shensha.data as any)[yearNayin];
            if (yearNayinData && liunian && yearNayinData === liunian) {
              matchedByLiunian = true;
            }
          }
          
          // 如果通过特殊处理匹配，添加神煞
          if (matchedByLiunian && !result.includes(shensha.name)) {
            result.push(shensha.name);
          }
        }
      }
    }
  }

  // 去重
  let uniqueShensha = Array.from(new Set(result));

  // 特殊处理：学堂类神煞的优先级
  const finalResult: string[] = [];
  
  // 先处理正版本
  for (const shensha of uniqueShensha) {
    if (shensha === '正学堂' || shensha === '正词馆') {
      finalResult.push(shensha);
    }
  }
  
  // 再处理普通版本，但跳过已有正版本的
  for (const shensha of uniqueShensha) {
    if (shensha === '学堂' || shensha === '词馆') {
      const positiveName = shensha === '学堂' ? '正学堂' : '正词馆';
      if (!finalResult.includes(positiveName)) {
        finalResult.push(shensha);
      }
    } else if (shensha !== '正学堂' && shensha !== '正词馆') {
      finalResult.push(shensha);
    }
  }

  // 排序
  finalResult.sort((a, b) => {
    const indexA = ssSequenceList.indexOf(a);
    const indexB = ssSequenceList.indexOf(b);
    return (indexA === -1 ? 999 : indexA) - (indexB === -1 ? 999 : indexB);
  });

  return finalResult;
}

